import cv2
import os
from my_align112x112 import face_align
import numpy as np
from my_facedet import face_det,scale32
from config import cfg_mnet


# t1 = np.array([-0.4,0.8,0.5,-0.2,0.3])
# t2 = np.array([-0.5,0.4,-0.2,0.7,-0.1])
def get_face_feature(detector,recongizer,img):
    """
    detector:检测器
    recongizer:特征提取器
    img:图片
    """
    #人脸检测
    img = scale32(img)
    dets,landms = face_det(detector,img)
    #人脸对齐
    face = face_align(img,landms[0])
    #特征提取
    feature = recongizer.feature(face)[0]
    return feature




def cos_sim(A,B):
    """
    计算相识度
    A:是特征 行向量
    B:是特征 列向量
    """
    modA = np.sum(((A-0)**2)) ** (1/2)#数值每个元素 0  平方 求和 开方
    modB = np.sum(((A-0)**2)) ** (1/2)
    #算AB的点积
    dotAB = np.dot(A,B.T)
    #余弦值
    cos = dotAB/(modA*modB)#范围[-1,1]
    #转为相识度形式：[-1,1]转为[0,1]
    sim = (cos+1)/2
    return sim


#     A_norm = np.linalg.norm(A)
#     B_norm = np.linalg.norm(B)
#     cos = np.dot(A,B)/(A_norm*B_norm)
#     return cos
# print(cos_sim(t1,t2))

def math_cos1(A,B):
    num = np.dot(A,B)
    denom = np.linalg.norm(A) * np.linalg.norm(B)
    cos1 = num / denom
    return cos1
# print(math_cos1(t2,t1))



def load_detector_recongizer(path1,path2):
    #加载模型
    net = cv2.dnn.readNet(path1)
    # cfg['pretrain'] = False
    # net = RetinaFace(cfg=cfg,phase = 'test')#搭建网络层
    # net = load_model(net,path1,True)#把训练好的参数放入网络层
    # net.eval()
    # 加载提取特征器
    recongizer = cv2.FaceRecognizerSF.create(path2, "")
    return net,recongizer

if __name__ == "__main__":
    cfg=cfg_mnet
    #人脸检测
    from models.retinaface import RetinaFace
    from detect import load_model
    from data.config import cfg_mnet
    from data.config import cfg_re50
    from my_facedet import face_det

    #判断同一个人的相似阈值
    lmit = 0.8


    cfg = cfg_mnet
    #加载模型
    # net = cv2.dnn.readNet("../models/FaceDetector.onnx")
    net = RetinaFace(cfg=cfg,phase = 'test')#搭建网络层
    net = load_model(net,"./weights/Resnet50_Final.pth",True)#把训练好的参数放入网络层
    net.eval()

    # 加载提取特征器
    recongizer = cv2.FaceRecognizerSF.create("../models/face_recognizer_fast.onnx", "")
    # 提取特征
    #feature = recongizer.feature(align_face)[0] # 提取特征

    #读取图片
    names = os.listdir("./curve/ylp")
    for name in names:
        image = cv2.imread("./curve/ylp/" + name)
        feature1 = get_face_feature(net,recongizer,image)
        names2 = os.listdir("./curve/wyz")
        for name2 in names2:
            if name == name2:
                continue
            image = cv2.imread("./curve/wyz/"+name2)
            feature2 = get_face_feature(net,recongizer,image)
            # print(feature1,len(feature1))
            #特征比较
            sim  = cos_sim(feature1,feature2)
            # print("相似度：{}%".format(sim*100))

            #验证：
            #1、同一个人的两张图片
            #2、不同人的两张图片
            if sim > lmit:
                print("{},{}的相似度：{}%，是同一个人".format(name,name2,sim*100))
            else:
                print("{},{}的相似度：{}%，不是同一个人".format(name,name2,sim*100))
        

    # #人脸检测
    # dets ,landms = face_det(net,image)
    # #人脸对齐
    # face2 = face_align(image,landms[0])